import utils from './utils'
import Geom from './geom'

const internal = {
  context: createContext(),
}
internal.getStateVar = function(key) {
  return internal.context[key]
}
internal.setStateVar = function(key, val) {
  internal.context[key] = val
}
function createContext() {
  return {
    input_files: [],
  }
}
function absArcId(arcId) {
  return arcId >= 0 ? arcId : ~arcId
}
internal.getWorldBounds = function(e) {
  e = utils.isFiniteNumber(e) ? e : 1e-10
  return [-180 + e, -90 + e, 180 - e, 90 - e]
}
function probablyDecimalDegreeBounds(b) {
  const world = internal.getWorldBounds(-1) // add a bit of excess
  const bbox = (b instanceof Bounds) ? b.toArray() : b
  return Geom.containsBounds(world, bbox)
}
function layerHasGeometry(lyr) {
  return layerHasPaths(lyr) || layerHasPoints(lyr)
}
function layerHasPaths(lyr) {
  return (lyr.geometry_type == 'polygon' || lyr.geometry_type == 'polyline') &&
    layerHasNonNullShapes(lyr)
}
function layerHasPoints(lyr) {
  return lyr.geometry_type == 'point' && layerHasNonNullShapes(lyr)
}
function layerHasNonNullShapes(lyr) {
  return utils.some(lyr.shapes || [], (shp) => {
    return !!shp
  })
}
function getFeatureCount(lyr) {
  let count = 0
  if (lyr.data) {
    count = lyr.data.size()
  } else if (lyr.shapes) {
    count = lyr.shapes.length
  }
  return count
}
export default {
  internal,
  probablyDecimalDegreeBounds,
  absArcId,
  layerHasPoints,
  layerHasPaths,
  layerHasGeometry,
  probablyDecimalDegreeBounds,
  getFeatureCount,
}